﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using eTerm.ASynClientSDK.Base;
using System.Text.RegularExpressions;

namespace eTerm.ASynClientSDK
{
    /// <summary>
    /// 从服务器获取当用户的PNR列表
    /// </summary>
    public sealed class PNRCommand : ASyncPNCommand
    {
        private int m_PageId = 1;

        /// <summary>
        /// 指令结果解析适配器.
        /// </summary>
        /// <param name="Msg">指令结果集合.</param>
        /// <returns></returns>
        protected override ASyncResult ResultAdapter(string Msg)
        {
            PNResult Result = new PNResult() { PnrList=new List<string>() };
            foreach (Match m in Regex.Matches(Msg, @"\s+\d+\s+([A-Z0-9]{6})\s+\d{4}-\d{2}-\d{2}\s\d{2}\:\d{2}\:\d{2}", RegexOptions.IgnoreCase | RegexOptions.Multiline))
            {
                Result.PnrList.Add(m.Groups[1].Value);
            }
            return Result;
        }

        /// <summary>
        /// 是否还有下页数据（将自动执行“PnCommand”）.
        /// </summary>
        /// <param name="msgBody">当前指令结果.</param>
        /// <returns></returns>
        /// <value><c>true</c> if [exist next page]; otherwise, <c>false</c>.</value>
        protected override bool ExistNextPage(string msgBody)
        {
            Match m = Regex.Match(msgBody, @"当前:\s+(\d+)\s+页\s+共:\s+(\d+)\s+页", RegexOptions.IgnoreCase | RegexOptions.Multiline);
            return m.Groups[1].Value != m.Groups[2].Value;
        }

        /// <summary>
        /// 下页指令.
        /// </summary>
        /// <value>The pn command.</value>
        protected override string PnCommand
        {
            get
            {
                return string.Format(@"!PNR {0}", ++m_PageId);
            }
        }

        /// <summary>
        /// Gets the PNR list.
        /// </summary>
        /// <returns></returns>
        public ASyncResult GetPnrList() {
            return base.GetSyncResult(string.Format( @"!PNR {0}",m_PageId));
        }
    }
}
